package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryParamHolder;
import com.mallcai.bigdata.ladon.service.report.impl.handler.support.ParamNameParser;
import com.mallcai.bigdata.ladon.utils.CollectionUtils;
import com.mallcai.bigdata.ladon.utils.SqlUtils;
import com.mallcai.bigdata.ladon.vo.Pair;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants.PARAM_PLACE_HOLDER;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 11:08
 */
@Slf4j
@Component
@Order(6000)
public class ComputeUsedParamHandler extends AbstractReportQueryPreHandler {

    @Override
    public void preInternal(ReportQueryContext context) {
        String sql = context.getSql();
        Map<String, ReportQueryParamHolder> allParams = context.getQueryParams();
        List<String> paramNames = ParamNameParser.parseParamName(sql);
        if(CollectionUtils.isNotEmpty(paramNames)){
            LinkedHashMap<Integer, Pair<ReportQueryParamHolder,Object>> sqlParams = new LinkedHashMap<>();
            String temp = sql;
            int index = 1;
            for (int i = 0; i < paramNames.size(); i++) {
                String paramName = paramNames.get(i);
                ReportQueryParamHolder reportQueryParamHolder = allParams.get(paramName);
                Object value = reportQueryParamHolder.getValue();
                String placeHolder = PARAM_PLACE_HOLDER;
                if(CollectionUtils.isCollection(value)){
                    Collection valueList = (Collection)value;
                    for(Object obj : valueList){
                        sqlParams.put(index++, new Pair<>(reportQueryParamHolder, obj));
                    }
                    placeHolder = CollectionUtils.join(valueList, x->PARAM_PLACE_HOLDER);
                } else {
                    sqlParams.put(index++,new Pair<>(reportQueryParamHolder, value));
                }
                temp = temp.replaceFirst(reportQueryParamHolder.toParamNamePattern(), placeHolder);
            }
            context.setSqlParams(sqlParams);
            context.setSql(temp);
            log.debug("替换前的sql:{},\n 替换后的sql:{}",sql, temp);
        }
    }
}
